import { query } from '../config/db.js';
import logger from '../config/logger.js';
import seedUsers from './seeders/seed_users.js';
import seedPermissions from './seeders/seed_permissions.js';
import seedRoles from './seeders/seed_roles.js';
import seedNewStudents from './seeders/seed_new_students.js';
import seedClubs from './seeders/seed_clubs.js';
import seedClubRegistrations from './seeders/seed_club_registrations.js';
import seedSeckillClubConfig from './seeders/seed_seckill_club_config.js';

async function seedDatabase() {
  try {
    logger.info('开始数据库播种...');

    // 运行各个种子脚本
    // await seedUsers();
    // await seedPermissions();
    // await seedRoles();
    // await seedNewStudents();
    // await seedClubs();
    // await seedClubRegistrations();
    // await seedSeckillClubConfig();
    
    return;

    // 关联表 user_permissions 中生成种子数据，用户表和权限表有记录，才能在用户权限表生成记录
    // 为管理员用户分配权限 (使用INSERT IGNORE避免重复插入)
    await query(
      `INSERT IGNORE INTO user_permissions (user_id, permission_id) 
       SELECT u.id, p.id FROM users u, permissions p 
       WHERE u.username = ?`,
      ['admin']
    );
    logger.info('已为管理员用户分配所有权限');

    // 为普通用户分配读取权限 (使用INSERT IGNORE避免重复插入)
    await query(
      `INSERT IGNORE INTO user_permissions (user_id, permission_id) 
       SELECT u.id, p.id FROM users u, permissions p 
       WHERE u.username = ? AND p.name IN (?, ?)`,
      ['user', 'read_users', 'read_permissions']
    );
    logger.info('已为普通用户分配读取权限');

    // 关联表 user_roles 中生成种子数据，用户表和角色表有记录，才能在用户角色表生成记录
    // 为用户分配角色 (使用INSERT IGNORE避免重复插入)
    await query(
      `INSERT IGNORE INTO user_roles (user_id, role_id) 
       SELECT u.id, r.id FROM users u, roles r 
       WHERE (u.username = ? AND r.name = ?) OR 
             (u.username = ? AND r.name = ?)`,
      ['admin', 'admin', 'user', 'user']
    );
    logger.info('已为用户分配角色');

    logger.info('数据库播种完成');
  } catch (error) {
    logger.error('数据库播种失败:', error);
    throw error;
  }
}

// 执行播种
seedDatabase().catch(error => {
  logger.error('数据库播种过程中出错:', error);
  process.exit(1);
});